extends NodeFinder


class_name TargetFinder
"""
查找目标
"""


enum Mode {
    ## 顺序
    ByOrder,
    ## 距离
    ByDistance,
}


## 检测逻辑
@export var mode: Mode = Mode.ByOrder
## 需要查找的分组
@export var group: String = ""
## 检测区域(未设置则全局获取)
@export var detect_area2d: Area2D = null


var bodies: Array[Node2D] = []


func __init_hooks() -> Dictionary:
    var hooks: Dictionary = {
        detect_area2d.body_entered: on_body_entered,
        detect_area2d.body_exited: on_body_exited,
    } if detect_area2d else {}
    return IComponent.merge(hooks, super.__init_hooks())

func on_body_entered(body: Node2D) -> void:
    if bodies.is_empty():
        event_target_changed.emit(self, null, body)
    bodies.append(body)

func on_body_exited(body: Node2D) -> void:
    bodies.erase(body)
    event_target_changed.emit(self, body, __inline_find())

func __inline_find() -> Node:
    var nodes: Array = []
    if detect_area2d == null:
        if group != "":
            nodes = get_tree().get_nodes_in_group(group)
    else:
        if group != "":
            for n in bodies:
                if n.is_in_group(group):
                    nodes.append(n)
        else:
            nodes = bodies
    if nodes.size() > 0:
        match mode:
            Mode.ByOrder:
                return nodes[0]
    return null
